<template>
  <div class="captcha-container">
    <label>图形验证码</label>
    <div class="captcha-input-row">
      <input
        type="text"
        v-model="inputCode"
        placeholder="请输入图形验证码"
        required
        @input="handleInput"
      />
      <div class="captcha-image-wrapper" @click="refreshCaptcha">
        <img 
          v-if="captchaImage" 
          :src="'data:image/png;base64,' + captchaImage" 
          alt="验证码"
          class="captcha-image"
        />
        <div v-else class="captcha-loading">加载中...</div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { getCaptcha, refreshCaptcha as refreshCaptchaApi } from '@/api/auth' // 修改导入的函数名

const inputCode = ref('')
const captchaImage = ref('')
const captchaId = ref('')
const isRefreshing = ref(false)

const emit = defineEmits(['update:modelValue'])

// 处理输入变化
const handleInput = () => {
  emit('update:modelValue', {
    captchaId: captchaId.value,
    captchacode: inputCode.value
  })
}

// 获取验证码
const fetchCaptcha = async () => {
  try {
    const response = await getCaptcha()
    
    console.log(response)
    captchaImage.value = response.data.captchaImage
    captchaId.value = response.data.captchaId
    handleInput() // 初始化时触发更新
  } catch (error) {
    console.error('获取验证码失败:', error)
  }
}

// 刷新验证码 - 使用新的函数名
const refreshCaptcha = async () => {
  if (isRefreshing.value || !captchaId.value) return
  
  isRefreshing.value = true
  try {
    const response = await refreshCaptchaApi(captchaId.value) // 使用修改后的函数名
    captchaImage.value = response.data.captchaImage
    captchaId.value = response.data.captchaId
    inputCode.value = ''
    handleInput()
  } catch (error) {
    console.error('刷新验证码失败:', error)
    await fetchCaptcha()
  } finally {
    isRefreshing.value = false
  }
}

// 初始化时获取验证码
onMounted(() => {
  fetchCaptcha()
})
</script>

<style scoped>
.captcha-container {
  margin-bottom: 10px;
}

.captcha-container label {
  display: block;
  margin-bottom: 6px;
  font-size: 0.9rem;
  color: var(--text-primary);
  font-weight: 500;
}

.captcha-input-row {
  display: flex;
  gap: 10px;
}

.captcha-input-row input {
  flex: 1;
  padding: 9px 1px;
  border: 1px solid rgba(var(--border-color-rgb), 0.3);
  border-radius: 6px;
  background: var(--surface);
  color: var(--text-primary);
  font-size: 0.95rem;
  transition: all 0.3s ease;
}

.captcha-input-row input:focus {
  border-color: var(--primary);
  box-shadow: 0 0 0 2px rgba(var(--primary-rgb), 0.2);
  outline: none;
}

.captcha-image-wrapper {
  width: 150px;
  height: 50px;
  border: 1px solid rgba(var(--border-color-rgb), 0.3);
  border-radius: 6px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
  background-color: #f5f5f5;
}

.captcha-image {
  width: 100px;
  height:100px;
  object-fit: contain;
}

.captcha-loading {
  color: var(--text-secondary);
  font-size: 0.8rem;
}
</style>